package com.kgc.scd.listener;

import com.alibaba.fastjson.JSON;
import com.kgc.scd.Constant.AccountMQConstant;
import com.kgc.scd.annotation.RequestShopUser;
import com.kgc.scd.config.AccountMQConfig;
import com.kgc.scd.entity.ShopGoods;
import com.kgc.scd.entity.ShopUser;
import com.kgc.scd.service.ShopGoodsServerService;
import com.kgc.scd.service.ShopOrderServerService;
import com.kgc.scd.service.ShopUserServerService;
import com.kgc.scd.util.RedisUtils;
import com.kgc.scd.vo.ShopGoodsVO;
import com.kgc.scd.vo.ShopOrderVO;
import com.kgc.scd.vo.ShopOrderitemVO;
import com.kgc.scd.vo.ShopUserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Created On : 2022/11/19.
 * <p>
 * Author : Administrator
 * <p>
 * Description: NormalPayedSuccessListener
 */
@Slf4j
@Component
@RabbitListener(queues = AccountMQConstant.NORMAL_PAY_RESULT_ORDER_QUEUE_TEST)
public class NormalPayedSuccessListener {


    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private ShopUserServerService shopUserServerService;

    @Autowired
    private ShopOrderServerService shopOrderServerService;

    @Autowired
    private ShopGoodsServerService shopGoodsServerService;

    /**
     * Created On : 2022/11/19.
     * <p>
     * Author : Administrator
     * <p>
     * Description: 收到成功信息开始结算
     */
    @RabbitHandler
    public void settlement(Map<String, Object> payResultMap){

        log.info("返回的结果集合:"+payResultMap);
        String orderId= (String) payResultMap.get("orderId");
        log.info("listen:"+orderId);

        //修改订单状态
        ShopOrderVO shopOrderVO=JSON.parseObject(redisUtils.get(orderId).toString(),ShopOrderVO.class);
        shopOrderVO.setShoppingStatus("支付成功/未发货");
        shopOrderServerService.updateSHopOrderStatus(shopOrderVO);

        ShopOrderitemVO shopOrderitemVO=shopOrderVO.getShopOrderitemVO();

        //获取消费数量,针对对应商品减库存
        String goodsId=shopOrderitemVO.getGoodsId();
        int number=shopOrderitemVO.getNumber();
        ShopGoodsVO shopGoodsVO=shopGoodsServerService.getShopGoodsById(goodsId);
        shopGoodsServerService.updateShopGoodsSubSellVolumeById(shopGoodsVO,number);

        //换取积分
        ShopUser shopUser=new ShopUser();
        String userId=shopOrderitemVO.getUserId();
        ShopUserVO shopUserV0=shopUserServerService.getShopUserById(userId);
        BeanUtils.copyProperties(shopUserV0,shopUser);
        double realPrice=shopOrderVO.getActualPrice();
        int jifen= (int) (realPrice/10);
        shopUser.setIntegration(shopUser.getIntegration()+jifen);
        shopUserServerService.updateShopUserByEntity(shopUser);
    }
}
